<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>localStorage</h1>
    <input type="text" name="key" id="">
    <input type="text" name="val" id="">
    <button>设置存储</button>
    <button>获取存储</button>
    <button>删除存储</button>
    <button>获取存储长度</button>
    <button>清空存储</button>
    <script>
        let inps = document.querySelectorAll('input');
        let btns = document.querySelectorAll('button');
        
        // 1. 设置localStorage属性 setItem(key,val)
        btns[0].onclick = function(){
            localStorage.setItem(inps[0].value,inps[1].value)
        }
        // 2. 获取localStorage属性 getItem(key);
        btns[1].onclick  =function(){
            let val = localStorage.getItem('username');
            alert(val);
        }

        // 3. 删除localStorage属性 removeItem(key);
        btns[2].onclick = function(){
            localStorage.removeItem('username2')
        }

        // 4. 获取localStorage的length 属性
        btns[3].onclick = function(){
           alert(localStorage.length);
        }

        // 5. 清空localStorage的数据
        btns[4].onclick = function(){
            localStorage.clear();
        }
        
        // 6. 当存储内容有变化时 监听 window.onstorage
        window.onstorage = function(){
            alert('改变了');
        }


    </script>
</body>
</html>